<template>
  <div class="content-page bg-gray-50 min-h-screen">
    <!-- 顶部导航栏 -->
    <div class="header-bar bg-white shadow-sm">
      <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center">
          <i class="fa fa-id-card text-blue-500 text-xl mr-2"></i>
          <h1 class="text-xl font-semibold text-gray-800">特殊人群认证管理系统</h1>
        </div>
        <div class="flex items-center space-x-4">
          <!-- <button class="logout-btn text-gray-500 hover:text-red-500 transition-colors flex items-center">
            <i class="fa fa-sign-out-alt mr-1"></i>
            <span class="hidden sm:inline">退出登录</span>
          </button> -->
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-6">
      <!-- 步骤条 -->
      <div class="step-bar mb-8 bg-white rounded-xl shadow-sm p-6">
        <div class="step-bar-container flex justify-between">
          <div class="step-item flex flex-col items-center" :class="{ active: step >= 1 }">
            <div class="step-number flex items-center justify-center w-12 h-12 rounded-full mb-2 text-lg font-bold shadow-md" :class="{ 'bg-blue-600 text-white ring-4 ring-blue-200': step >= 1, 'bg-gray-200 text-gray-500': step < 1 }">
              1
            </div>
            <span class="step-text text-sm font-medium" :class="{ 'text-blue-600': step >= 1, 'text-gray-500': step < 1 }">选择认证类型</span>
          </div>
          <div class="step-line flex-1 h-1 mx-2 my-6 relative">
            <div class="absolute inset-0 bg-gray-200 rounded-full"></div>
            <div class="absolute inset-y-0 left-0 bg-blue-600 rounded-full transition-all duration-500" :style="{ width: step >= 2 ? '100%' : '0%' }"></div>
          </div>
          <div class="step-item flex flex-col items-center" :class="{ active: step >= 2 }">
            <div class="step-number flex items-center justify-center w-12 h-12 rounded-full mb-2 text-lg font-bold shadow-md" :class="{ 'bg-blue-600 text-white ring-4 ring-blue-200': step >= 2, 'bg-gray-200 text-gray-500': step < 2 }">
              2
            </div>
            <span class="step-text text-sm font-medium" :class="{ 'text-blue-600': step >= 2, 'text-gray-500': step < 2 }">上传材料</span>
          </div>
          <div class="step-line flex-1 h-1 mx-2 my-6 relative">
            <div class="absolute inset-0 bg-gray-200 rounded-full"></div>
            <div class="absolute inset-y-0 left-0 bg-blue-600 rounded-full transition-all duration-500" :style="{ width: step >= 3 ? '100%' : '0%' }"></div>
          </div>
          <div class="step-item flex flex-col items-center" :class="{ active: step >= 3 }">
            <div class="step-number flex items-center justify-center w-12 h-12 rounded-full mb-2 text-lg font-bold shadow-md" :class="{ 'bg-blue-600 text-white ring-4 ring-blue-200': step >= 3, 'bg-gray-200 text-gray-500': step < 3 }">
              3
            </div>
            <span class="step-text text-sm font-medium" :class="{ 'text-blue-600': step >= 3, 'text-gray-500': step < 3 }">填写信息</span>
          </div>
          <div class="step-line flex-1 h-1 mx-2 my-6 relative">
            <div class="absolute inset-0 bg-gray-200 rounded-full"></div>
            <div class="absolute inset-y-0 left-0 bg-blue-600 rounded-full transition-all duration-500" :style="{ width: step >= 4 ? '100%' : '0%' }"></div>
          </div>
          <div class="step-item flex flex-col items-center" :class="{ active: step >= 4 }">
            <div class="step-number flex items-center justify-center w-12 h-12 rounded-full mb-2 text-lg font-bold shadow-md" :class="{ 'bg-blue-600 text-white ring-4 ring-blue-200': step >= 4, 'bg-gray-200 text-gray-500': step < 4 }">
              4
            </div>
            <span class="step-text text-sm font-medium" :class="{ 'text-blue-600': step >= 4, 'text-gray-500': step < 4 }">提交成功</span>
          </div>
        </div>
      </div>

      <!-- 认证类型选择区域 -->
      <div v-if="step === 1" class="certification-types mb-8 bg-white rounded-xl shadow-sm p-6">
        <h2 class="text-2xl font-bold mb-6 text-gray-800">请选择您的认证类型</h2>
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
          <div class="cert-type-card" :class="{ selected: selectedCertType === 'disabled' }" @click="selectCertType('disabled')">
            <div class="card-content p-6 rounded-xl border-2 transition-all duration-300 hover:shadow-md" :class="{ 'border-blue-500 bg-blue-50': selectedCertType === 'disabled', 'border-gray-200 hover:border-blue-300 hover:bg-blue-50/50': selectedCertType !== 'disabled' }">
              <div class="flex items-start">
                <div class="icon-container w-14 h-14 rounded-full flex items-center justify-center mr-4 shadow-sm" :class="{ 'bg-blue-100': selectedCertType === 'disabled', 'bg-blue-50': selectedCertType !== 'disabled' }">
                  <i class="fa fa-wheelchair text-blue-600 text-2xl"></i>
                </div>
                <div class="flex-1">
                  <h3 class="font-semibold text-lg text-gray-800">残疾人认证</h3>
                  <p class="text-sm text-gray-600 mt-2">为残疾人提供的专属服务认证</p>
                </div>
              </div>
            </div>
          </div>
          
          <div class="cert-type-card" :class="{ selected: selectedCertType === 'elderly' }" @click="selectCertType('elderly')">
            <div class="card-content p-6 rounded-xl border-2 transition-all duration-300 hover:shadow-md" :class="{ 'border-green-500 bg-green-50': selectedCertType === 'elderly', 'border-gray-200 hover:border-green-300 hover:bg-green-50/50': selectedCertType !== 'elderly' }">
              <div class="flex items-start">
                <div class="icon-container w-14 h-14 rounded-full flex items-center justify-center mr-4 shadow-sm" :class="{ 'bg-green-100': selectedCertType === 'elderly', 'bg-green-50': selectedCertType !== 'elderly' }">
                  <i class="fa fa-user text-green-600 text-2xl"></i>
                </div>
                <div class="flex-1">
                  <h3 class="font-semibold text-lg text-gray-800">单亲家庭认证</h3>
                  <p class="text-sm text-gray-600 mt-2">为单亲家庭提供的专属服务认证</p>
                </div>
              </div>
            </div>
          </div>
          
          <div class="cert-type-card" :class="{ selected: selectedCertType === 'lowIncome' }" @click="selectCertType('lowIncome')">
            <div class="card-content p-6 rounded-xl border-2 transition-all duration-300 hover:shadow-md" :class="{ 'border-yellow-500 bg-yellow-50': selectedCertType === 'lowIncome', 'border-gray-200 hover:border-yellow-300 hover:bg-yellow-50/50': selectedCertType !== 'lowIncome' }">
              <div class="flex items-start">
                <div class="icon-container w-14 h-14 rounded-full flex items-center justify-center mr-4 shadow-sm" :class="{ 'bg-yellow-100': selectedCertType === 'lowIncome', 'bg-yellow-50': selectedCertType !== 'lowIncome' }">
                  <i class="fa fa-money-check text-yellow-600 text-2xl"></i>
                </div>
                <div class="flex-1">
                  <h3 class="font-semibold text-lg text-gray-800">低收入家庭认证</h3>
                  <p class="text-sm text-gray-600 mt-2">为低收入家庭提供的专属服务认证</p>
                </div>
              </div>
            </div>
          </div>
          
          <div class="cert-type-card" :class="{ selected: selectedCertType === 'veteran' }" @click="selectCertType('veteran')">
            <div class="card-content p-6 rounded-xl border-2 transition-all duration-300 hover:shadow-md" :class="{ 'border-red-500 bg-red-50': selectedCertType === 'veteran', 'border-gray-200 hover:border-red-300 hover:bg-red-50/50': selectedCertType !== 'veteran' }">
              <div class="flex items-start">
                <div class="icon-container w-14 h-14 rounded-full flex items-center justify-center mr-4 shadow-sm" :class="{ 'bg-red-100': selectedCertType === 'veteran', 'bg-red-50': selectedCertType !== 'veteran' }">
                  <i class="fa fa-medal text-red-600 text-2xl"></i>
                </div>
                <div class="flex-1">
                  <h3 class="font-semibold text-lg text-gray-800">退伍军人认证</h3>
                  <p class="text-sm text-gray-600 mt-2">为退伍军人提供的专属服务认证</p>
                </div>
              </div>
            </div>
          </div>
          
          <div class="cert-type-card" :class="{ selected: selectedCertType === 'other' }" @click="selectCertType('other')">
            <div class="card-content p-6 rounded-xl border-2 transition-all duration-300 hover:shadow-md" :class="{ 'border-purple-500 bg-purple-50': selectedCertType === 'other', 'border-gray-200 hover:border-purple-300 hover:bg-purple-50/50': selectedCertType !== 'other' }">
              <div class="flex items-start">
                <div class="icon-container w-14 h-14 rounded-full flex items-center justify-center mr-4 shadow-sm" :class="{ 'bg-purple-100': selectedCertType === 'other', 'bg-purple-50': selectedCertType !== 'other' }">
                  <i class="fa fa-question-circle text-purple-600 text-2xl"></i>
                </div>
                <div class="flex-1">
                  <h3 class="font-semibold text-lg text-gray-800">其他特殊群体认证</h3>
                  <p class="text-sm text-gray-600 mt-2">为其他特殊群体提供的专属服务认证</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 上传材料区域 -->
      <div v-if="step === 2" class="upload-section mb-8 bg-white rounded-xl shadow-sm p-6">
        <h2 class="text-2xl font-bold mb-6 text-gray-800">上传证明材料</h2>
        
        <div class="upload-instructions mb-6 bg-blue-50 border border-blue-200 rounded-lg p-5">
          <h3 class="font-semibold text-lg text-blue-700 flex items-center">
            <i class="fa fa-info-circle mr-2"></i> 上传说明
          </h3>
          <ul class="mt-3 text-sm text-blue-700 space-y-2">
            <li class="flex items-start">
              <i class="fa fa-check-circle text-blue-500 mt-1 mr-2"></i>
              <span>请上传与您申请的认证类型相关的证明材料</span>
            </li>
            <li class="flex items-start">
              <i class="fa fa-check-circle text-blue-500 mt-1 mr-2"></i>
              <span>支持格式：JPG, PNG, PDF, DOCX</span>
            </li>
            <li class="flex items-start">
              <i class="fa fa-check-circle text-blue-500 mt-1 mr-2"></i>
              <span>单个文件大小不超过5MB</span>
            </li>
            <li class="flex items-start">
              <i class="fa fa-check-circle text-blue-500 mt-1 mr-2"></i>
              <span>您可以上传多张证明材料</span>
            </li>
          </ul>
        </div>
        
        <div class="upload-options flex flex-col md:flex-row gap-5 mb-6">
          <button class="upload-btn flex-1 flex items-center justify-center py-5 px-6 border-2 border-dashed border-gray-300 rounded-xl hover:border-blue-500 hover:bg-blue-50 transition-all duration-300 group" @click="triggerUpload">
            <div class="flex items-center">
              <i class="fa fa-cloud-upload-alt text-gray-400 text-3xl mr-3 group-hover:text-blue-500"></i>
              <div class="text-left">
                <div class="text-base font-medium text-gray-700 group-hover:text-blue-600">从本地上传文件</div>
                <div class="text-xs text-gray-500">点击或拖拽文件至此处</div>
              </div>
            </div>
          </button>
          
          <button class="upload-btn flex-1 flex items-center justify-center py-5 px-6 border-2 border-dashed border-gray-300 rounded-xl hover:border-blue-500 hover:bg-blue-50 transition-all duration-300 group" @click="openCamera">
            <div class="flex items-center">
              <i class="fa fa-camera text-gray-400 text-3xl mr-3 group-hover:text-blue-500"></i>
              <div class="text-left">
                <div class="text-base font-medium text-gray-700 group-hover:text-blue-600">拍照上传</div>
                <div class="text-xs text-gray-500">使用摄像头拍摄材料</div>
              </div>
            </div>
          </button>
        </div>
        
        <!-- 已上传文件列表 -->
        <div v-if="uploadedFiles.length > 0" class="uploaded-files mt-6">
          <h3 class="font-semibold text-lg text-gray-800 mb-4">已上传文件</h3>
          <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
            <div v-for="(file, index) in uploadedFiles" :key="index" class="file-item bg-gray-50 rounded-lg p-4 flex items-center shadow-sm hover:shadow-md transition-shadow">
              <div class="file-icon w-12 h-12 rounded bg-blue-100 flex items-center justify-center mr-4">
                <i class="fa fa-file-pdf text-blue-600 text-xl"></i>
              </div>
              <div class="flex-1 min-w-0">
                <p class="file-name text-sm font-medium text-gray-800 truncate">{{ file.name }}</p>
                <p class="file-size text-xs text-gray-500">{{ file.size }}</p>
              </div>
              <button class="delete-file text-gray-400 hover:text-red-500 transition-colors" @click="removeFile(index)">
                <i class="fa fa-times text-lg"></i>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 认证信息填写区域 -->
      <div v-if="step === 3" class="info-form mb-8 bg-white rounded-xl shadow-sm p-6">
        <h2 class="text-2xl font-bold mb-6 text-gray-800">填写认证信息</h2>
        
        <form @submit.prevent="submitForm">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">姓名 <span class="text-red-500">*</span></label>
              <div class="relative">
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <i class="fa fa-user text-gray-400"></i>
                </div>
                <input type="text" v-model="formData.name" class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all" placeholder="请输入姓名">
                <div v-if="!formData.name && submitted" class="text-red-500 text-xs mt-1">请输入姓名</div>
              </div>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">身份证号码 <span class="text-red-500">*</span></label>
              <div class="relative">
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <i class="fa fa-id-card text-gray-400"></i>
                </div>
                <input type="text" v-model="formData.idNumber" class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all" placeholder="请输入身份证号码">
                <div v-if="!formData.idNumber && submitted" class="text-red-500 text-xs mt-1">请输入身份证号码</div>
                <div v-if="formData.idNumber && !/^\d{17}[\dXx]$/.test(formData.idNumber) && submitted" class="text-red-500 text-xs mt-1">请输入有效的18位身份证号码</div>
              </div>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">联系电话 <span class="text-red-500">*</span></label>
              <div class="relative">
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <i class="fa fa-phone text-gray-400"></i>
                </div>
                <input type="tel" v-model="formData.phone" class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all" placeholder="请输入联系电话">
                <div v-if="!formData.phone && submitted" class="text-red-500 text-xs mt-1">请输入联系电话</div>
                <div v-if="formData.phone && !/^1[3-9]\d{9}$/.test(formData.phone) && submitted" class="text-red-500 text-xs mt-1">请输入有效的手机号码</div>
              </div>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">电子邮箱</label>
              <div class="relative">
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <i class="fa fa-envelope text-gray-400"></i>
                </div>
                <input type="email" v-model="formData.email" class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all" placeholder="请输入电子邮箱">
                <div v-if="formData.email && !/\S+@\S+\.\S+/.test(formData.email) && submitted" class="text-red-500 text-xs mt-1">请输入有效的电子邮箱</div>
              </div>
            </div>
          </div>
          
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-2">特殊情况详细描述 <span class="text-red-500">*</span></label>
            <div class="relative">
              <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <i class="fa fa-file-text text-gray-400"></i>
              </div>
              <textarea v-model="formData.description" rows="4" class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all" placeholder="请详细描述您的特殊情况"></textarea>
                <div v-if="!formData.description && submitted" class="text-red-500 text-xs mt-1">请填写特殊情况详细描述</div>
            </div>
          </div>
          
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-2">附加说明（可选）</label>
            <div class="relative">
              <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <i class="fa fa-comment text-gray-400"></i>
              </div>
              <textarea v-model="formData.additionalInfo" rows="3" class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all" placeholder="如有其他需要说明的情况，请在此处填写"></textarea>
            </div>
          </div>
          
          <div class="flex items-start mb-6">
            <div class="flex items-center h-5 mt-1">
              <input id="privacy" name="privacy" type="checkbox" v-model="privacyAccepted" class="w-5 h-5 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500">
            </div>
            <div class="ml-3 text-sm">
              <label for="privacy" class="text-gray-600">我已阅读并同意 <a href="#" class="text-blue-500 hover:underline">《隐私政策》</a> 和 <a href="#" class="text-blue-500 hover:underline">《认证服务条款》</a></label>
            </div>
            <div v-if="!privacyAccepted && submitted" class="text-red-500 text-xs mt-1">请阅读并同意隐私政策和服务条款</div>
          </div>
        </form>
      </div>

      <!-- 提交成功区域 -->
      <div v-if="step === 4" class="success-section mb-8 bg-white rounded-xl shadow-sm p-6 text-center">
        <div class="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6 shadow-sm">
          <i class="fa fa-check text-green-600 text-3xl"></i>
        </div>
        <h2 class="text-2xl font-bold mb-3 text-gray-800">认证申请已提交成功</h2>
        <p class="text-gray-600 mb-6">
          您的认证申请已成功提交，我们将在3个工作日内完成审核
          <br>审核结果将通过短信通知您
        </p>
        <div class="bg-gray-50 rounded-lg p-4 max-w-md mx-auto mb-6">
          <div class="flex justify-between items-center">
            <span class="text-gray-600">申请编号</span>
            <span class="font-medium">{{ applicationNumber }}</span>
          </div>
          <div class="flex justify-between items-center mt-2">
            <span class="text-gray-600">提交时间</span>
            <span>{{ submissionTime }}</span>
          </div>
          <div class="flex justify-between items-center mt-2">
            <span class="text-gray-600">预计审核完成</span>
            <span>{{ estimatedCompletionTime }}</span>
          </div>
        </div>
        <button @click="backToHome" class="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-all shadow-sm hover:shadow">
          返回首页
        </button>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons flex justify-end space-x-4 mt-8" v-if="step < 4">
        <button v-if="step > 1" @click="prevStep" class="px-6 py-3 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-all flex items-center">
          <i class="fa fa-arrow-left mr-2"></i> 上一步
        </button>
        <button @click="nextStep" class="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-all flex items-center shadow-sm hover:shadow">
          {{ step === 3 ? '提交认证申请' : '下一步' }}
          <i class="fa fa-arrow-right ml-2" v-if="step < 3"></i>
        </button>
      </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 py-8 mt-16">
      <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
        <p>© 2025 特殊人群认证管理系统. 保留所有权利.</p>
        <p class="mt-2">如有疑问，请联系客服：400-123-4567</p>
      </div>
    </footer>

    <!-- 隐藏的文件输入 -->
    <input type="file" ref="fileInput" @change="handleFileChange" style="display: none;" multiple>
    
    <!-- 摄像头模态框 -->
    <div v-if="isCameraOpen" class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-80">
      <div class="bg-white rounded-xl p-4 max-w-2xl w-full mx-4">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-xl font-bold text-gray-800">拍照上传</h3>
          <button @click="closeCamera" class="text-gray-500 hover:text-gray-700">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
        <div class="relative">
          <video ref="videoElement" autoplay class="w-full h-auto rounded-lg border border-gray-200"></video>
          <div class="absolute bottom-4 left-1/2 transform -translate-x-1/2 flex space-x-4">
            <button @click="capturePhoto" class="bg-blue-600 hover:bg-blue-700 text-white rounded-full w-14 h-14 flex items-center justify-center shadow-lg">
              <i class="fa fa-camera text-2xl"></i>
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 错误提示模态框 -->
    <div v-if="errorMessage" class="fixed inset-0 flex items-center justify-center z-50 bg-black bg-opacity-50">
      <div class="bg-white rounded-lg p-6 max-w-md w-full mx-4 shadow-xl transform transition-all">
        <h3 class="text-xl font-bold text-gray-800 mb-4">提交失败</h3>
        <p class="text-gray-600 mb-6" v-html="errorMessage"></p>
        <div class="flex justify-end">
          <button @click="closeErrorModal" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
            确定
          </button>
        </div>
      </div>
    </div>

    <!-- 网络错误提示 -->
    <div v-if="networkError" class="fixed bottom-4 right-4 bg-red-500 text-white px-4 py-3 rounded-lg shadow-lg transform transition-all duration-300">
      <div class="flex items-center">
        <i class="fa fa-exclamation-circle mr-2"></i>
        <span>{{ networkError }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

// 状态管理
const step = ref(1);
const selectedCertType = ref('');
const uploadedFiles = ref([]);
const fileInput = ref(null);
const formData = ref({
  name: '',
  idNumber: '',
  phone: '',
  email: '',
  description: '',
  additionalInfo: '',
  certType: '',
  files: []
});
const privacyAccepted = ref(false);
const loading = ref(false);
const submitted = ref(false);
const errorMessage = ref('');
const networkError = ref('');
const isCameraOpen = ref(false);
const videoElement = ref(null);
const stream = ref(null);

// 提交成功后显示的信息
const applicationNumber = ref('');
const submissionTime = ref('');
const estimatedCompletionTime = ref('');

// 认证类型数据
const certTypes = [
  { id: 'disabled', name: '残疾人认证', icon: 'fa-wheelchair', color: 'blue' },
  { id: 'elderly', name: '单亲家庭', icon: 'fa-user', color: 'green' },
  { id: 'lowIncome', name: '低收入家庭认证', icon: 'fa-money-check', color: 'yellow' },
  { id: 'veteran', name: '退伍军人认证', icon: 'fa-medal', color: 'red' },
  { id: 'other', name: '其他特殊群体认证', icon: 'fa-question-circle', color: 'purple' }
];

// 选择认证类型
const selectCertType = (type) => {
  selectedCertType.value = type;
  formData.value.certType = type;
  ElMessage({
    message: `已选择${certTypes.find(t => t.id === type).name}`,
    type: 'success',
    center: true
  });
};

// 触发文件上传
const triggerUpload = () => {
  fileInput.value?.click();
};

// 处理文件上传
const handleFileChange = (event) => {
  const files = event.target.files;
  const allowedExtensions = ['.jpg', '.png', '.pdf', '.docx'];
  if (files.length > 0) {
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
      if (file.size > 5 * 1024 * 1024) { // 5MB限制
        ElMessage({
          message: '文件大小不能超过5MB',
          type: 'error',
          center: true
        });
        continue;
      }
      if (!allowedExtensions.includes(fileExtension)) {
        ElMessage({
          message: '不支持的文件类型，请上传JPG、PNG、PDF或DOCX格式的文件',
          type: 'error',
          center: true
        });
        continue;
      }

      const fileInfo = {
        name: file.name,
        size: formatFileSize(file.size),
        file: file
      };

      uploadedFiles.value.push(fileInfo);
      formData.value.files.push(file);
    }
    ElMessage({
      message: '文件上传成功',
      type: 'success',
      center: true
    });
  }
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 打开摄像头
const openCamera = async () => {
  try {
    stream.value = await navigator.mediaDevices.getUserMedia({ video: true });
    videoElement.value.srcObject = stream.value;
    videoElement.value.play();
    isCameraOpen.value = true;
  } catch (err) {
    ElMessage({
      message: '无法访问摄像头，请确保您已授予权限',
      type: 'error',
      center: true
    });
    console.error('访问摄像头失败:', err);
  }
};

// 关闭摄像头
const closeCamera = () => {
  if (stream.value) {
    stream.value.getTracks().forEach(track => track.stop());
    stream.value = null;
  }
  isCameraOpen.value = false;
};

// 拍照
const capturePhoto = () => {
  if (!videoElement.value) return;
  
  const canvas = document.createElement('canvas');
  canvas.width = videoElement.value.videoWidth;
  canvas.height = videoElement.value.videoHeight;
  const ctx = canvas.getContext('2d');
  ctx.drawImage(videoElement.value, 0, 0, canvas.width, canvas.height);
  
  // 将Canvas转换为Blob对象
  canvas.toBlob((blob) => {
    const file = new File([blob], `photo_${new Date().getTime()}.jpg`, { type: 'image/jpeg' });
    const fileInfo = {
      name: file.name,
      size: formatFileSize(file.size),
      file: file
    };
    
    uploadedFiles.value.push(fileInfo);
    formData.value.files.push(file);
    
    ElMessage({
      message: '照片已成功拍摄并上传',
      type: 'success',
      center: true
    });
    
    closeCamera();
  }, 'image/jpeg', 0.8);
};

// 下一步
const nextStep = () => {
  // 重置提交状态
  submitted.value = false;
  networkError.value = '';
  
  // 步骤验证
  if (step.value === 1 && !selectedCertType.value) {
    ElMessage({
      message: '请选择认证类型',
      type: 'warning',
      center: true
    });
    return;
  }
  
  if (step.value === 2 && uploadedFiles.value.length === 0) {
    ElMessage({
      message: '请上传证明材料',
      type: 'warning',
      center: true
    });
    return;
  }
  
  if (step.value === 3) {
    submitted.value = true;
    
    // 表单验证
    const validationErrors = [];
    
    if (!formData.value.name) {
      validationErrors.push('请输入姓名');
    }
    
    if (!formData.value.idNumber) {
      validationErrors.push('请输入身份证号码');
    } else if (!/^\d{17}[\dXx]$/.test(formData.value.idNumber)) {
      validationErrors.push('请输入有效的18位身份证号码');
    }
    
    if (!formData.value.phone) {
      validationErrors.push('请输入联系电话');
    } else if (!/^1[3-9]\d{9}$/.test(formData.value.phone)) {
      validationErrors.push('请输入有效的手机号码');
    }
    
    if (!formData.value.description) {
      validationErrors.push('请填写特殊情况详细描述');
    }
    
    if (uploadedFiles.value.length === 0) {
      validationErrors.push('请上传证明材料');
    }
    
    if (!privacyAccepted.value) {
      validationErrors.push('请阅读并同意隐私政策和服务条款');
    }
    
    // 显示所有验证错误
    if (validationErrors.length > 0) {
      errorMessage.value = validationErrors.join('<br>');
      return;
    }
    
    // 如果是最后一步，提交表单
    submitForm();
    return;
  }
  
  // 进入下一步
  step.value++;
};

// 上一步
const prevStep = () => {
  if (step.value > 1) {
    step.value--;
  }
};

// 移除文件
const removeFile = (index) => {
  uploadedFiles.value.splice(index, 1);
  formData.value.files.splice(index, 1);
};

// 关闭错误模态框
const closeErrorModal = () => {
  errorMessage.value = '';
};

// 关闭网络错误提示
const closeNetworkError = () => {
  networkError.value = '';
};

// 返回首页
const backToHome = () => {
  // 重置表单
  step.value = 1;
  selectedCertType.value = '';
  uploadedFiles.value = [];
  formData.value = {
    name: '',
    idNumber: '',
    phone: '',
    email: '',
    description: '',
    additionalInfo: '',
    certType: '',
    files: []
  };
  privacyAccepted.value = false;
  submitted.value = false;
  applicationNumber.value = '';
  submissionTime.value = '';
  estimatedCompletionTime.value = '';
  networkError.value = '';
};

// 模拟获取token
const getToken = () => {
  // 实际应用中应从存储中获取token
  return 'your_token_here';
};

// 提交表单
const submitForm = async () => {
  // 表单验证
  const validationErrors = [];
  
  if (!formData.value.name) {
    validationErrors.push('请输入姓名');
  }
  
  if (!formData.value.idNumber) {
    validationErrors.push('请输入身份证号码');
  } else if (!/^\d{17}[\dXx]$/.test(formData.value.idNumber)) {
    validationErrors.push('请输入有效的18位身份证号码');
  }
  
  if (!formData.value.phone) {
    validationErrors.push('请输入联系电话');
  } else if (!/^1[3-9]\d{9}$/.test(formData.value.phone)) {
    validationErrors.push('请输入有效的手机号码');
  }
  
  if (!formData.value.description) {
    validationErrors.push('请填写特殊情况详细描述');
  }
  
  if (uploadedFiles.value.length === 0) {
    validationErrors.push('请上传证明材料');
  }
  
  if (!privacyAccepted.value) {
    validationErrors.push('请阅读并同意隐私政策和服务条款');
  }
  
  // 显示所有验证错误
  if (validationErrors.length > 0) {
    errorMessage.value = validationErrors.join('<br>');
    return;
  }
  
  // 显示加载状态
  loading.value = true;
  const submitBtn = document.querySelector('.action-buttons button:last-child');
  if (submitBtn) {
    submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 提交中...';
    submitBtn.disabled = true;
  }
  
  try {
    // 准备表单数据
    const form = new FormData();
    
    // 添加文件
    if (formData.value.files && formData.value.files.length > 0) {
      formData.value.files.forEach((file, index) => {
        form.append(`files[${index}]`, file);
      });
    }
    
    // 添加认证信息
    form.append('certificationData', JSON.stringify({
      certType: formData.value.certType,
      name: formData.value.name,
      idNumber: formData.value.idNumber,
      phone: formData.value.phone,
      email: formData.value.email,
      description: formData.value.description,
      additionalInfo: formData.value.additionalInfo
    }));
    
    // 打印调试信息
    console.log('准备提交的表单数据:', form);
    
    // 调用API
    const response = await axios.post(
      'http://localhost:8081/certificateAuthority/addSpecialGroup',
      form,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${getToken()}`
        },
        onUploadProgress: (progressEvent) => {
          // 显示上传进度
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          console.log(`上传进度: ${percentCompleted}%`);
          // 这里可以添加进度条显示
        }
      }
    );
    
    // 打印响应信息
    console.log('API响应:', response.data);
    
    // 处理响应
    if (response.status === 200 && response.data && response.data.success) {
      // 更新提交成功信息
      applicationNumber.value = response.data.applicationNumber || 'AP' + Math.floor(Math.random() * 1000000);
      const now = new Date();
      submissionTime.value = now.toLocaleString();
      
      // 计算预计完成时间（3个工作日后）
      const estimatedDate = new Date(now);
      let workingDaysAdded = 0;
      while (workingDaysAdded < 3) {
        estimatedDate.setDate(estimatedDate.getDate() + 1);
        // 跳过周末
        if (estimatedDate.getDay() !== 0 && estimatedDate.getDay() !== 6) {
          workingDaysAdded++;
        }
      }
      estimatedCompletionTime.value = estimatedDate.toLocaleDateString();
      
      // 进入提交成功页面
      step.value = 4;
      
      // 记录成功日志
      console.log('认证申请提交成功');
    } else {
      // 处理API返回的错误
      let errorMsg = '认证申请提交失败';
      
      // 根据不同的错误类型提供更详细的提示
      if (response.data && response.data.errorCode) {
        switch (response.data.errorCode) {
          case 'INVALID_ID_NUMBER':
            errorMsg = '身份证号码格式不正确，请检查后重新提交';
            break;
          case 'DUPLICATE_APPLICATION':
            errorMsg = '您已提交过相同类型的认证申请，请勿重复提交';
            break;
          case 'FILE_UPLOAD_ERROR':
            errorMsg = '文件上传失败，请检查文件格式和大小后重试';
            break;
          default:
            errorMsg = response.data.message || '认证申请提交失败，请稍后重试';
        }
      }
      
      errorMessage.value = errorMsg;
    }
  } catch (error) {
    // 处理网络错误
    console.error('提交表单时发生错误:', error);
    networkError.value = '网络连接失败，请检查您的网络设置并稍后重试';
    
    // 可以根据不同的错误类型提供不同的提示
    if (error.response) {
      // 服务器返回了错误状态码
      console.error('服务器响应错误:', error.response.status);
      if (error.response.status === 401) {
        networkError.value = '认证失败，请重新登录';
        // 可以在这里添加重新登录的逻辑
      } else if (error.response.status === 403) {
        networkError.value = '权限不足，无法完成此操作';
      } else if (error.response.status === 500) {
        networkError.value = '服务器内部错误，请稍后重试';
      }
    } else if (error.request) {
      // 请求已发送，但没有收到响应
      console.error('没有收到服务器响应:', error.request);
      networkError.value = '无法连接到服务器，请检查您的网络连接';
    } else {
      // 发生了其他错误
      console.error('发生错误:', error.message);
      networkError.value = '发生未知错误，请稍后重试';
    }
  } finally {
    // 重置加载状态
    loading.value = false;
    if (submitBtn) {
      submitBtn.innerHTML = step.value === 3 ? '提交认证申请' : '下一步';
      submitBtn.disabled = false;
    }
  }
};

// 生命周期钩子
onMounted(() => {
  // 页面加载完成后执行的操作
  console.log('认证表单组件已加载');
});

onUnmounted(() => {
  // 组件卸载前执行的操作
  if (stream.value) {
    stream.value.getTracks().forEach(track => track.stop());
    stream.value = null;
  }
});
</script>

<style scoped>
/* 步骤条样式 */
.step-bar {
  background-color: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.step-bar-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}

.step-item {
  z-index: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.step-number {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  font-size: 18px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.step-text {
  margin-top: 8px;
  font-size: 14px;
  font-weight: 500;
  transition: color 0.3s ease;
}

.step-line {
  position: relative;
  height: 4px;
  background-color: #e5e7eb;
  border-radius: 2px;
  z-index: 0;
}

/* 认证类型卡片样式 */
.cert-type-card {
  cursor: pointer;
  transition: transform 0.3s ease;
}

.cert-type-card:hover {
  transform: translateY(-4px);
}

.card-content {
  border-radius: 16px;
  transition: all 0.3s ease;
}

.icon-container {
  transition: all 0.3s ease;
}

/* 上传按钮样式 */
.upload-btn {
  transition: all 0.3s ease;
}

.upload-btn:hover {
  transform: translateY(-2px);
}

/* 文件项样式 */
.file-item {
  transition: all 0.3s ease;
}

.file-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

.delete-file {
  transition: all 0.3s ease;
}

.delete-file:hover {
  transform: scale(1.1);
}

/* 表单输入样式 */
input:focus,
textarea:focus {
  transition: all 0.3s ease;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.3);
}

/* 按钮样式 */
button {
  transition: all 0.3s ease;
}

button:hover:not(:disabled) {
  transform: translateY(-2px);
}

/* 响应式布局 */
@media (max-width: 768px) {
  .step-number {
    width: 36px;
    height: 36px;
    font-size: 14px;
  }
  
  .step-text {
    font-size: 12px;
  }
  
  .upload-options {
    flex-direction: column;
  }
  
  .upload-btn {
    margin-bottom: 1rem;
  }
  
  .grid-cols-2, .grid-cols-3 {
    grid-template-columns: 1fr;
  }
}

/* 错误提示样式 */
.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

/* 成功消息样式 */
.success-message {
  color: #52c41a;
  font-size: 12px;
  margin-top: 4px;
}

/* 加载状态样式 */
.loading {
  cursor: not-allowed;
  opacity: 0.7;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  max-width: 500px;
  width: 90%;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 平滑滚动 */
html {
  scroll-behavior: smooth;
}

/* 自定义动画 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { transform: translateY(20px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

.animate-fade-in {
  animation: fadeIn 0.3s ease-out forwards;
}

.animate-slide-up {
  animation: slideUp 0.4s ease-out forwards;
}

/* 表单验证动画 */
@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
  20%, 40%, 60%, 80% { transform: translateX(5px); }
}

.input-error {
  animation: shake 0.5s ease-in-out;
  border-color: #ff4d4f !important;
}
</style>  